/**
 * @file    drv_can.h
 * @author  yhy
 * @brief   芯必达IM94x系列芯片, can抽象层
 * @version 1.02
 * @date    2025-07-07
 *
 * @copyright Copyright (c) 2025
 *
 * @details
 * Change Logs:
 * Date           Author       Notes
 * 2025-07-07     yhy          the first version V1.00
 * 2025-07-11     yhy          所有函数和变量名修改为snf_开头 V1.01
 * 2025-07-16     yhy          修复了snf_drv_can_convert_errcode函数传入ERR_SUCCESS返回ERROR的BUG V1.02
 *
 */
#ifndef __DRV_CAN_H__
#define __DRV_CAN_H__

#include "common_config.h"

#include <stdbool.h>
#include <stdint.h>

#define CAN_FILTER_MAXSIZE      3           /* CAN过滤器数量 */
#define CAN_INSTANCE_MAXSIZE    (4 + 3 + 2) /* CAN实例数量, CAN0-4个, CAN1-3个, CAN2-2个 */
#define CAN_HW_INSTANCE_MAXSIZE 3           /* 硬件CAN实例数量 */

/* CAN回调函数类型 */
typedef void (*can_callback_f)(uint32_t instance, void *param);

/**
 * @brief CAN帧结构体
 *
 */
typedef struct
{
    uint32_t std_id;   /*!< 标准ID */
    uint8_t  dlc;      /*!< 数据长度 */
    uint8_t  data[64]; /*!< 数据 */
} snf_can_frame_t;

/**
 * @brief CAN实例
 *
 */
typedef enum
{
    CAN_INSTANCE_CAN0_0 = 0U, /*!< CAN0, tx: PE5, rx: PE4 */
    CAN_INSTANCE_CAN0_1 = 1U, /*!< CAN0, tx: PC3, rx: PC2 */
    CAN_INSTANCE_CAN0_2 = 2U, /*!< CAN0, tx: PB1, rx: PB0 */
    CAN_INSTANCE_CAN0_3 = 3U, /*!< CAN0, tx: PA3, rx: PA2 */
    CAN_INSTANCE_CAN1_0 = 4U, /*!< CAN1, tx: PA6, rx: PE7 */
    CAN_INSTANCE_CAN1_1 = 5U, /*!< CAN1, tx: PC7, rx: PC6 */
    CAN_INSTANCE_CAN1_2 = 6U, /*!< CAN1, tx: PA13, rx: PA12 */
    CAN_INSTANCE_CAN2_0 = 7U, /*!< CAN1, tx: PC17, rx: PC16 */
    CAN_INSTANCE_CAN2_1 = 8U, /*!< CAN1, tx: PB13, rx: PB12 */
} snf_can_instance_e;

/**
 * @brief   CAN过滤器结构体
 * @details 芯必达的mask对应的位为0时，该位参与过滤
 *
 */
typedef struct
{
    uint32_t code; /*!< CAN过滤码 */
    uint32_t mask; /*!< CAN过滤码掩码 */
} snf_can_filter_t;

/**
 * @brief CAN配置结构体
 *
 */
typedef struct
{
    snf_can_instance_e instance;                   /*!< CAN实例，根据实例选择CAN及其PIN */
    bool               fd_enable;                  /*!< 是否使能CAN-FD */
    snf_can_filter_t   filter[CAN_FILTER_MAXSIZE]; /*!< CAN过滤器配置 */
    can_callback_f     tx_callback;                /*!< CAN-Tx回调函数 */
    void              *tx_callback_param;          /*!< CAN-Tx回调函数参数 */
    can_callback_f     rx_callback;                /*!< CAN-Rx回调函数 */
    void              *rx_callback_param;          /*!< CAN-Rx回调函数参数 */
} snf_can_config_t;

result_e snf_drv_can_init(const snf_can_config_t *can_init_config);
result_e snf_drv_can_deinit(snf_can_instance_e instance);
result_e snf_drv_can_transmit(snf_can_instance_e instance, const snf_can_frame_t *frame);

#endif
